<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <title>Markdown预览工具</title>
    <uieip type="file" value="inc" src="/yqwin/easyui/include.txt" cache="true" minute="1440"></uieip>
    <uieip type="file" value="css" src="/yqwin/css/yqwin.min" cache="false"></uieip>
    <uieip type="file" value="js" src="/yqwin/data/yqwin.min" cache="false"></uieip>
    <script src="/scripts/marked/marked.min.js"></script>
    <script src="/scripts/marked/highlight.min.js"></script>
    <script src="/scripts/marked/highlightjs-line-numbers.min.js"></script>

    <link href="/scripts/marked/css/font.css" rel="stylesheet" />
    <link rel="stylesheet" href="/scripts/marked/css/markdown-light.css" />
    <style>
        .container {
            padding: 50px;
            width: 80%;
            max-width: 900px;
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <a href="javascript:window.history.back();">返回</a>
    <div class="container">
        <div id="pretitle"></div>
        <div id="preview"></div>
    </div>


    <script>


        const markdownText = `
# 单一组件
## 1.lable
\`\`\`json
{
	"default": null
}
\`\`\`
|#|name|类型|默认值|说明|
|-|----|---|------|----|
|1|default|string|null|默认值|
## 2.textbox
\`\`\`json
{
   "default": null,
   "blank": true,
   "min": null,
   "max": null,
   "format": ""
}
\`\`\`
|#|name|类型|默认值|说明|
|-|----|---|------|----|
|1|default|string|null|默认值|
|2|blank|bool|true|是否运行为空，默认允许为空|
|3|min|int|null|最小长度，默认不校验最小长度|
|4|max|int|null|最大长度，默认不校验最大长度|
|5|format|string|""|字符串校验掩码 长度按半角计算，数字、英文为1，中文为2。|


# 标题1

\`\`\`javascript
function calculate() {
    // 示例代码
    const a = 1;
    const b = 2;
    return a + b;
}

function copyToClipboard(text) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text)
            .then(() => {
                console.log('文本已成功拷贝到剪贴板: ' + text);
            })
            .catch((err) => {
                console.error('无法拷贝文本: ', err);
            });
    } else {
        console.error('当前浏览器不支持 navigator.clipboard');
        // 使用兼容性方法
        copyToClipboardFallback(text);
    }
}

// 兼容性方法
function copyToClipboardFallback(text) {
    var textarea = document.createElement('textarea');
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    try {
        var successful = document.execCommand('copy');
        var msg = successful ? '成功' : '失败';
        console.log('拷贝文本 ' + msg);
    } catch (err) {
        console.error('无法拷贝文本: ', err);
    }
    document.body.removeChild(textarea);
}

// 使用示例
copyToClipboard('你好，世界！');
\`\`\`

\`\`\`python
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)
\`\`\`
`;

        $(document).ready(function () {
            const $preview = $('#preview');
            const $pretitle = $('#pretitle');
            $.yqMdView({
                mdText: markdownText,
                $view: $preview,
                $title: $pretitle
            });
        });
    </script>

    <script>
        //markdown view
        jQuery.extend({
            yqMdView: function (opts) {
                if (opts.mdText === undefined) {
                    opts.mdText = "";
                }

                var doc = generateMarkdownWithToc(opts.mdText);
                if (!(opts.$title === undefined) && opts.$title.length > 0) {
                    opts.$title.addClass("markdown-title");
                    opts.$title.html(doc.toc);
                }

                if (opts.$view === undefined || opts.$view.length == opts) {
                    return;
                }

                opts.$view.addClass("markdown-body");
                opts.$view.html(doc.html);
                // 高亮代码块
                opts.$view.find('pre code').each(function () {
                    const block = $(this);
                    try {
                        hljs.highlightElement(block[0]);
                        hljs.lineNumbersBlock(block[0]);
                    } catch (error) {
                        console.error('代码块高亮失败:', error);
                    }

                    // 获取代码块的语言类型
                    const codeLang = block.attr('class').replace('hljs', '').replace('language-', '').trim();

                    // 创建代码块标题
                    const codeTitle = $('<div class="code-title"></div>').text(codeLang);

                    // 创建复制按钮
                    const copyButton = createCopyButton(block);

                    // 将代码块标题和复制按钮添加到代码块的父元素（pre）中
                    const preElement = block.parent();
                    preElement.css('position', 'relative');
                    preElement.prepend(codeTitle);
                    preElement.append(copyButton);
                });

                function createCopyButton(block) {
                    const copyButton = $('<button class="copy-button">复制</button>');

                    // 复制按钮点击事件
                    copyButton.on('click', async function () {
                        const codeContent = block.text().trim();
                        if (!codeContent) {
                            console.warn('代码块内容为空');
                            return;
                        }

                        try {
                            await copyToClipboard(codeContent);
                            copyButton.text('已复制');
                            setTimeout(() => {
                                copyButton.text('复制');
                            }, 3000);
                        } catch (err) {
                            console.error('复制失败:', err);
                        }
                    });

                    return copyButton;
                }

                async function copyToClipboard(text) {
                    if (navigator.clipboard) {
                        try {
                            await navigator.clipboard.writeText(text);
                            console.log('文本已成功拷贝到剪贴板: ' + text);
                        } catch (err) {
                            console.error('无法拷贝文本: ', err);
                            copyToClipboardFallback(text);
                        }
                    } else {
                        console.error('当前浏览器不支持 navigator.clipboard');
                        copyToClipboardFallback(text);
                    }
                }

                function copyToClipboardFallback(text) {
                    const textarea = $('<textarea></textarea>').val(text);
                    $('body').append(textarea);
                    textarea.select();
                    try {
                        const successful = document.execCommand('copy');
                        const msg = successful ? '成功' : '失败';
                        console.log('拷贝文本 ' + msg);
                    } catch (err) {
                        console.error('无法拷贝文本: ', err);
                    } finally {
                        textarea.remove();
                    }
                }

                function generateMarkdownWithToc(markdown) {
                    const headings = [];

                    // 自定义 renderer
                    const renderer = {
                        heading(token) {
                            return `<h${token.depth} id="${token.id}">${token.text}</h${token.depth}>`;
                        }
                    };

                    // 使用自定义 renderer
                    marked.use({ renderer });

                    const html = marked.parse(markdown, {
                        walkTokens: function (token) {
                            if (token.type === 'heading') {
                                token.id = $.getShortID();
                                headings.push({ level: token.depth, text: token.text, id: token.id });
                            }
                        }
                    });

                    let toc = '<ul>';
                    let currentLevel = 1;

                    headings.forEach(heading => {
                        if (heading.level > currentLevel) {
                            toc += '<ul>';
                        } else if (heading.level < currentLevel) {
                            toc += '</ul>'.repeat(currentLevel - heading.level);
                        }
                        toc += `<li><a href="#${heading.id}">${heading.text}</a></li>`;
                        currentLevel = heading.level;
                    });

                    toc += '</ul>'.repeat(currentLevel - 1);

                    return { html, toc };
                }
            }
        });

    </script>
</body>

</html>